package com.ophiux.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ophiux.common.core.constant.CacheConstants;
import com.ophiux.common.core.constant.SecurityConstants;
import com.ophiux.common.core.enums.ErrorCodesEnum;
import com.ophiux.common.core.enums.LoginTypeEnum;
import com.ophiux.common.core.utils.MsgUtils;
import com.ophiux.common.core.utils.R;
import com.ophiux.system.mapper.SysUserMapper;
import com.ophiux.system.model.entity.SysUser;
import com.ophiux.system.service.MobileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class MobileServiceImpl implements MobileService {

    private final RedisTemplate redisTemplate;

    private final SysUserMapper userMapper;

    /**
     * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
     *
     * @param mobile mobile
     * @return code
     */
    @Override
    public R<Boolean> sendSmsCode(String mobile) {
        List<SysUser> userList = userMapper.selectList(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, mobile));

        if (CollUtil.isEmpty(userList)) {
            log.info("手机号未注册:{}", mobile);
            return R.ok(Boolean.FALSE, ErrorCodesEnum.SYS_APP_PHONE_UNREGISTERED.getMessage());
        }

        Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile);

        if (codeObj != null) {
            log.info("手机号验证码未过期:{}，{}", mobile, codeObj);
            return R.ok(Boolean.FALSE, ErrorCodesEnum.SYS_APP_SMS_OFTEN.getMessage());
        }

        String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
        log.info("手机号生成验证码成功:{},{}", mobile, code);
        redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
        return R.ok(Boolean.TRUE, code);
    }

}
